package com.huaqin.punan.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class UserDAO {
	private DBOpenHelper helper;

	public UserDAO(Context context) {

		helper = new DBOpenHelper(context, DBOpenHelper.DBNAME, null, DBOpenHelper.VERSION);

	}

	/**
	 * 添加用户信息
	 */

	public void add(User user) {
		SQLiteDatabase db = helper.getWritableDatabase();

		String sql = "Insert into u_user(_id,name,age,tall) values(?,?,?,?)";
		db.execSQL(sql,
				new Object[] { user.getId(), user.getName(), user.getAge(),
						user.getTall() });
		db.close();
	}

	/**
	 * 删除用户信息
	 */
	public void delete(Integer... id) {
		if (id.length > 0) {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < id.length; i++) {
				sb.append("?").append(",");
			}
			sb.deleteCharAt(sb.length() - 1);
			SQLiteDatabase database = helper.getWritableDatabase();
			String sql = "delete from u_user where _id in (" + sb + ")";
			database.execSQL(sql, (Object[]) id);
		}
	}

	/**
	 * 删除表里的全部数据
	 */
	public void delelteall() {
		SQLiteDatabase database = helper.getWritableDatabase();
		String sql = "delete from u_user";
		database.execSQL(sql);
	}

	/**
	 * 用户修改
	 */
	public void update(User user) {
		SQLiteDatabase db = helper.getWritableDatabase();// 写入数据库中注意！！！！不能放在外面
		String sql = "update u_user set name=?,age=?,tall=? where _id=?";
		db.execSQL(sql,
				new Object[] { user.getName(), user.getAge(), user.getTall(),
						user.getId() });
	}

	/**
	 * 查找用户信息
	 */
	public User find(int userid) {
		SQLiteDatabase db = helper.getWritableDatabase();// 写入数据库中注意！！！！不能放在外面
		String sql = "select _id,name,age,tall from u_user where _id=?";
		Cursor cursor = db.rawQuery(sql,
				new String[] { String.valueOf(userid) });
		if (cursor.moveToNext()) {
			return new User(cursor.getInt(cursor.getColumnIndex("_id")),
					cursor.getString(cursor.getColumnIndex("name")),
					cursor.getInt(cursor.getColumnIndex("age")),
					cursor.getString(cursor.getColumnIndex("tall")));
		}
		return null;
	}

	/**
	 * 显示用户
	 */
	public Cursor select() {
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor = db.query("u_user", null, null, null, null, null,
				"_id desc");
		return cursor;
	}
}
